#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Tack application script for Apache mod_wsgi.

The mod_wsgi script handling leaves a bit to be desired.  This script
exists because we can't configure mod_wsgi on a per virtual host
basis.  So instead, when this script is run, it tweaks sys.path to
include the parent directory of this tack installation.
"""
import os
import sys


dirname = os.path.dirname
tackparentdir = dirname(dirname(dirname(dirname(__file__))))
tackdir = dirname(dirname(dirname(__file__)))


try:
    import tack
except (ImportError, ):
    if tackparentdir not in sys.path:
        sys.path.append(tackparentdir)


from tack.lib import not_found
from tack.lib.modtools import load_config, load_mods, load_urls
from tack.lib.dispatcher import dispatcher


def application(environ, start_response):
    """ Tack dispatcher for mod_wsgi.

    When an Apache server with mod_wsgi is configured to use this
    script, mod_wsgi will locate and call this function.

    When called, this function configures the environment, reads the
    url configuration, and defers to a dispatcher instance.

    @param environ WSGI environment
    @param start_response WSGI web server start response
    @return iterable response
    """
    environ['tack.siteconfig'] = cfg = load_config(environ)
    environ['tack.modules'] = mods = load_mods(cfg, environ)
    urls = [record for record in load_urls(mods) if record]
    dispatch = dispatcher(urls, handle404=not_found)
    return dispatch(environ, start_response)
